#pragma once

#include "Common.hpp"

#define CONV(ADDR) (struct sockaddr *)&ADDR

class InetAddr
{
public:
    InetAddr(sockaddr_in &addr)
        : _addr(addr)
    {
        // 网络转主机
        _port = ntohs(_addr.sin_port);
        char ipbuffer[64];
        inet_ntop(AF_INET, &_addr.sin_addr, ipbuffer, sizeof(_addr));
        _ip = ipbuffer;
    }

    InetAddr(std::string ip, uint16_t port)
        : _ip(ip), _port(port)
    {
        // 主机转网络
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
    }

    uint16_t Port() { return _port; }
    std::string Ip() { return _ip; }

    std::string AddrToString() const
    {
        return _ip + ":" + std::to_string(_port);
    }

    struct sockaddr_in &NetAddr() { return _addr; }

    struct sockaddr *NetAddrPtr() { return CONV(_addr); }

    socklen_t NetAddrLen() { return sizeof(_addr); }

    ~InetAddr() {}

private:
    sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
};